<template>
  <div class="user">
    <el-row style="height: 100%">
      <el-col :span="6" style="height: 100%">
        <pageCard :title-name="'部门树'" :type="'pageTitle'">
          <el-input v-model="filterText" placeholder="输入关键字进行过滤" style="padding-bottom: 10px" />
          <el-scrollbar style="height: calc(105% - 42px)" class="treeContent">
            <el-tree
              ref="tree"
              :data="departmentTree"
              default-expand-all
              node-key="id"
              highlight-current
              :expand-on-click-node="false"
              :filter-node-method="filterNode"
              :props="defaultProps"
              @node-click="nodeClick"
            >
              <span slot-scope="{ node }" class="treeRow">
                <i class="el-icon-office-building" />
                <span class="treeLabel">{{ node.label }}</span>
              </span>
            </el-tree>
          </el-scrollbar>
        </pageCard>
      </el-col>
      <el-col :span="18" style="height: 100%">
        <pageCard :title-name="'用户列表'" :type="'pageTitle'">
          <div class="topText">用户名称/登录名：</div>
          <el-input
            v-model="search.userName"
            placeholder="请输入"
            class="searchInput"
            @keyup.enter.native="searchClick"
          />
          <el-button type="primary" class="topBtn" icon="el-icon-search" @click="searchClick">搜索</el-button>
          <div class="topBtnDiv">
            <el-button type="primary" plain class="topBtn" @click="alertForm('add')">新增</el-button>
          </div>
          <myTable
            ref="myTable"
            style="margin-top: 10px"
            :row-key="'userId'"
            :table-label="tableLabel"
            :table-data="tableData"
            :table-total-size="tableTotalSize"
            :search-data="searchData"
            @getTableData="getTableData"
            @handleSelectionChange="handleSelectionChange"
            @rowClickChange="rowClickChange"
          >
            <template #operating="slotProps">
              <el-link
                v-if="slotProps.rowValue.userId !== 1"
                :underline="false"
                type="primary"
                @click="alertForm('edit', slotProps.rowValue)"
              >
                编辑
              </el-link>
              <el-divider v-if="slotProps.rowValue.userId !== 1" direction="vertical"></el-divider>
              <el-link
                v-if="slotProps.rowValue.userId !== 1"
                :underline="false"
                type="primary"
                @click="alertForm('role', slotProps.rowValue)"
              >
                设置角色
              </el-link>
              <el-divider v-if="slotProps.rowValue.userId !== 1" direction="vertical"></el-divider>
              <el-link :underline="false" type="primary" @click="dialogVisible = true">重置密码</el-link>
              <el-divider
                v-if="slotProps.rowValue.userId !== 1 && slotProps.rowValue.userId !== $store.state.user.id"
                direction="vertical"
              ></el-divider>
              <el-link
                v-if="slotProps.rowValue.userId !== 1 && slotProps.rowValue.userId !== $store.state.user.id"
                :underline="false"
                type="primary"
                style="color: red"
                @click="deleteClick(slotProps.rowValue)"
              >
                删除
              </el-link>
            </template>
          </myTable>
          <pagination
            class="myPagination"
            :table-total-size="tableTotalSize"
            :search-data="searchData"
            @getTableData="$refs.myTable.getTableData()"
          />
        </pageCard>
      </el-col>
    </el-row>
    <el-dialog title="新密码发送方式" :visible.sync="dialogVisible" width="35%" style="margin-top: 12vh">
      <div v-if="!resetSuccess">
        <el-row style="margin: 50px">
          <el-col :span="12">
            <div :class="resetClass[0]" @click="setResetCSS(0)">通过邮件发送</div>
          </el-col>
          <el-col :span="12">
            <div :class="resetClass[1]" @click="setResetCSS(1)">自行告知用户</div>
          </el-col>
        </el-row>
      </div>
      <span v-if="!resetSuccess" slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="resetPassword">重 置</el-button>
      </span>
      <div v-if="resetSuccess">
        <el-row style="margin: 50px" :gutter="40">
          <el-col :span="6" align="right">
            <p style="font-size: 18px">账号：</p>
            <p style="font-size: 18px">新密码：</p>
          </el-col>
          <el-col :span="18">
            <p style="font-size: 18px">{{ newLoginName }}</p>
            <p style="font-size: 18px">{{ newPassword }}</p>
          </el-col>
        </el-row>
        <p style="font-size: 18px; margin-left: 250px">请将新密码记录并告知用户</p>
      </div>
      <span v-if="resetSuccess" slot="footer" class="dialog-footer">
        <el-button @click="closeSuccessDialog">关 闭</el-button>
      </span>
    </el-dialog>
    <setUser
      v-if="['add', 'edit'].includes(pageType)"
      ref="setUser"
      @submitForm="submitForm"
      @closeForm="closeForm()"
    />
    <setUserRoles v-if="pageType === 'role'" ref="setUserRoles" @closeForm="closeForm" />
  </div>
</template>

<script>
import md5 from 'js-md5'
import {
  getUser,
  addUser,
  updateUser,
  deleteUser,
  getRoleIdsByUserId,
  sendUserPasswordEmail,
  resetPassword
} from '@/api/system-management'
import { getDepartmentNodeTree } from '@/api/table'
import setUser from './components/setUser'
import setUserRoles from './components/setUserRoles'
import pageCard from '@/components/page/pageCard'
import myTable from '@/components/Table/index'
import pagination from '@/components/Table/pagination'
import defaultSettings from '@/settings'
import { generateUUID, postMessage, receivedMessage } from '@/utils/index'
const { randomString } = require('@/utils')

export default {
  name: 'User',
  components: {
    pageCard,
    myTable,
    pagination,
    setUser,
    setUserRoles
  },
  data() {
    return {
      // 重置密码
      online: false,
      title: '新密码发送方式',
      resetSuccess: false,
      newLoginName: '',
      newPassword: '',
      resetClass: ['resetBox', 'resetBox'],
      dialogVisible: false,
      // 编辑页面type
      pageType: 'index',
      // 部门树
      filterText: '',
      departmentTree: [],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      // table需要的数据
      search: {
        userName: '',
        chooseDate: null
      },
      searchData: {
        pageSize: 15,
        currentPage: 1,
        sort: {},
        params: {}
      },
      tableData: [],
      tableLabel: [
        // {
        //   type: 'selection',
        //   width: '55'
        // },
        {
          prop: 'userId',
          label: '用户ID',
          width: 150,
          showOverflowTooltip: false
        },
        {
          prop: 'loginName',
          label: '登录账号',
          width: 200,
          showOverflowTooltip: false
        },
        {
          prop: 'userName',
          label: '用户名称',
          // minWidth: 120,
          width: 200,
          showOverflowTooltip: true
        },
        {
          prop: 'departmentName',
          label: '部门',
          width: 200,
          showOverflowTooltip: false
        },
        {
          prop: 'jobCode',
          label: '工号',
          width: 100,
          showOverflowTooltip: false
        },
        {
          prop: 'operating',
          label: '操作',
          fixed: 'right',
          type: 'scope',
          width: 300,
          showOverflowTooltip: false
        }
      ],
      tableTotalSize: null,
      multipleSelection: [],
      currentRow: {},
      getDepartmentNodeTreeRequestId: generateUUID(),
      getUserDataRequestId: generateUUID(),
      callbackFun: null
    }
  },

  watch: {
    filterText(val) {
      this.$refs.tree.filter(val)
    }
  },
  mounted() {
    this.getTreeData()

    receivedMessage(this.dataHandle)

    var i = new Image()
    i.src = 'https://www.baidu.com/img/PCtm_d9c8750bed0b3c7d089fa7d55720d6cf.png?t=' + Date.parse(new Date())
    var that = this
    i.onload = function () {
      that.online = true
    }
    i.onerror = function () {
      that.online = false
    }
  },
  methods: {
    dataHandle(result) {
      let self = this
      let e = defaultSettings.isWPF ? result : { data: JSON.parse(result) }
      if (e.data.webInfo.requestId === self.getDepartmentNodeTreeRequestId) {
        let res = e.data.response
        self.departmentTree.push(res.data)
      } else if (e.data.webInfo.requestId === self.getUserDataRequestId) {
        let res = e.data.response
        self.tableData = res.data
        self.tableTotalSize = res.total_count
        self.resetCurrentRow(self.currentRow.userId)
        self.callbackFun(res.data)
      }
    },
    // 用户提交
    submitForm(type, data, informType, originalPassword) {
      if (type === 'add') {
        addUser(data).then((res) => {
          if (informType === 'self') {
            this.dialogVisible = true
            this.resetSuccess = true
            this.newLoginName = data.loginName
            this.newPassword = originalPassword
          }
          if (informType === 'email') {
            sendUserPasswordEmail({ userId: res.id }).then((response) => {
              this.$notify({
                title: '成功',
                message: '已发送邮件',
                type: 'success'
              })
            })
          }
          this.$notify({
            title: '成功',
            message: '新增用户成功',
            type: 'success'
          })
          this.$refs.myTable.getTableData()
          this.closeForm()
        })
      }
      if (type === 'edit') {
        updateUser(data).then((res) => {
          this.$notify({
            title: '成功',
            message: '修改用户成功',
            type: 'success'
          })
          this.$refs.myTable.getTableData()
          this.closeForm()
        })
      }
    },
    // 重新获取当前选中行的数据
    resetCurrentRow(id) {
      for (const item of this.tableData) {
        if (id === item.userId) {
          this.currentRow = item
        }
      }
    },
    // 删除用户
    deleteClick(row) {
      this.$confirm('此操作将永久删除' + row.userName + '用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          deleteUser({ userId: row.userId }).then((res) => {
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
            this.$refs.myTable.getTableData()
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 关闭重置成功弹窗
    closeSuccessDialog() {
      this.dialogVisible = false
      setTimeout(() => {
        this.resetSuccess = false
      }, 400)
    },
    // 设置重置框css
    setResetCSS(index) {
      // index为0就是用邮件发送
      if (index === 0) {
        if (this.online) {
          this.resetClass = ['resetBoxChoose', 'resetBox']
        } else {
          this.$message({
            message: '需要联网才可以进行发送邮件操作',
            type: 'warning'
          })
        }
      }
      // index为1就是自行告知
      if (index === 1) {
        this.resetClass = ['resetBox', 'resetBoxChoose']
      }
    },

    // 重置密码
    resetPassword() {
      let resetIndex = null
      for (const index in this.resetClass) {
        if (this.resetClass[index] === 'resetBoxChoose') {
          resetIndex = index
        }
      }
      const originalPassword = randomString(8)
      const passwordMD5 = md5(originalPassword)
      switch (resetIndex) {
        case '0':
          sendUserPasswordEmail({ userId: this.currentRow.userId }).then((res) => {
            this.dialogVisible = false
            this.$notify({
              title: '成功',
              message: '已发送邮件',
              type: 'success'
            })
          })
          break
        case '1':
          resetPassword({ userId: this.currentRow.userId, password: passwordMD5 }).then((res) => {
            // this.dialogVisible = false
            this.resetSuccess = true
            this.newLoginName = res.data.loginName
            this.newPassword = originalPassword
          })
          break
        default:
          this.$message({
            message: '请先选择新密码告知方式再重置密码',
            type: 'warning'
          })
          break
      }
    },
    // 点击新增或者编辑
    alertForm(type, row) {
      this.pageType = type
      this.$nextTick(() => {
        if (type === 'edit') {
          for (const item of this.tableData) {
            if (item.userId === row.userId) {
              this.$refs.setUser.is(this.pageType, row)
            }
          }
        } else if (type === 'add') {
          this.$refs.setUser.is(this.pageType, row)
        } else {
          getRoleIdsByUserId({ userId: row.userId }).then((res) => {
            this.$refs.setUserRoles.is(row, res.data)
          })
        }
      })
    },
    // 关闭表单
    closeForm() {
      this.pageType = 'index'
    },
    // 获取tableData
    getTableData(cab) {
      if (defaultSettings.isWPF || defaultSettings.isCEF) {
        this.callbackFun = cab
        this.getUserDataRequestId = generateUUID()
        let message = {
          RequestUrl: process.env.VUE_APP_URL + '/vue/user/load',
          RequestMethod: 'POST',
          Headers: {
            contentType: 'application/json'
          },
          QueryParameter: {},
          RequestBody: this.searchData,
          WebInfo: {
            requestId: this.getUserDataRequestId
          }
        }
        postMessage(message)
      } else {
        getUser(this.searchData).then((res) => {
          this.tableData = res.data
          this.tableTotalSize = res.total_count
          this.resetCurrentRow(this.currentRow.userId)
          cab(res.data)
        })
        // return new Promise((resolve, reject) => {
        //   getUser(this.searchData).then(res => {
        //     this.tableData = res.data
        //     this.tableTotalSize = res.total_count
        //     this.resetCurrentRow(this.currentRow.userId)
        //     setTimeout(() => {
        //       resolve(this.tableData)
        //     }, 5000)
        //   }).catch(error => {
        //     reject(error)
        //   })
        // })
      }
    },
    // 搜索
    searchClick() {
      this.searchData.currentPage = 1
      this.searchData.params['userName'] = this.search.userName
      this.$refs.myTable.getTableData()
    },
    // 复选框回调函数
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    // 点击行回调函数
    rowClickChange(val) {
      this.currentRow = val
      // this.getBookingDevice(val.id)
    },
    // 获取数据
    getTreeData() {
      this.departmentTree = []

      if (defaultSettings.isWPF || defaultSettings.isCEF) {
        this.getDepartmentNodeTreeRequestId = generateUUID()
        let message = {
          RequestUrl: process.env.VUE_APP_URL + '/vue/department/loadTree',
          RequestMethod: 'POST',
          Headers: {
            contentType: 'application/json'
          },
          QueryParameter: {},
          RequestBody: {},
          WebInfo: {
            requestId: this.getDepartmentNodeTreeRequestId
          }
        }
        postMessage(message)
      } else {
        getDepartmentNodeTree().then((res) => {
          this.departmentTree.push(res.data)
        })
      }
    },
    // 以下树函数
    // 过滤树函数
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    // 点击节点
    nodeClick(node) {
      if (node.company) {
        this.searchData.params['departmentId'] = null
      } else {
        this.searchData.params['departmentId'] = node.id
      }
      this.$refs.myTable.getTableData()
    }
  }
}
</script>

<style lang="scss" scoped>
@import '../../styles/pageTableTop.scss';
@import '~@/styles/element-variables.scss';
.user {
  height: 99%;
  .resetBox {
    position: relative;
    width: 200px;
    height: 80px;
    margin: 0 30px;
    padding: 27px 45px;
    color: #aaaaaa;
    font-size: 17px;
    border: 2px solid #aaaaaa;
  }
  .resetBox:hover {
    box-sizing: border-box;
    border: 2px solid $--color-primary;
  }
  .resetBoxChoose {
    position: relative;
    width: 200px;
    height: 80px;
    margin: 0 30px;
    padding: 27px 45px;
    color: $--color-primary;
    font-size: 17px;
  }
  .resetBoxChoose {
    box-sizing: border-box;
    border: 3px solid $--color-primary;
  }
  .resetBoxChoose:before {
    content: '';
    display: block;
    position: absolute;
    right: 0;
    bottom: 0;
    border: 17px solid $--color-primary;
    border-top-color: transparent;
    border-left-color: transparent;
    color: #fff;
  }
  .resetBoxChoose:after {
    content: '';
    display: block;
    width: 5px;
    height: 12px;
    position: absolute;
    right: 6px;
    bottom: 6px;
    border: 2px solid #fff;
    border-top-color: transparent;
    border-left-color: transparent;
    transform: rotate(45deg);
  }
  .treeContent {
    /deep/.el-scrollbar__view {
      height: auto;
    }
  }
  /deep/.el-tree {
    border-right: none;
    .treeRow {
      width: 100%;
      display: flex;
      align-items: center;
      .treeLabel {
        font-size: 14px;
        padding-left: 5px;
      }
    }
    .el-tree-node__expand-icon {
      font-size: 18px;
      position: relative;
      left: 5px;
    }

    .el-tree-node .is-current {
      background-color: #f5f7fa;
    }
    .el-tree-node__expand-icon {
      float: right;
      // margin-right: 1.5625rem !important;
    }
    .el-tree-node__content {
      height: 2.5rem;
      line-height: 2.5rem;
      font-size: 16px;
    }
    .el-tree--highlight-current .el-tree-node.is-current > .el-tree-node__content {
      background: #ecf5ff;
    }
  }
  .myPagination /deep/.page {
    margin-bottom: -2px;
  }
}
</style>
